import 'dart:typed_data';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_shop/r.dart';
import 'package:flutter_shop/res/colors.dart';
import 'package:flutter_shop/utils/utils.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';

/// Title:网络图片加载 <br/>
/// Description: <br/>
/// author:xiemiao <br/>
/// date: 2020-03-12  <br/>
/// version 1.0 <br/>
class LoadImage extends StatelessWidget {
  final imageUrl;
  final double width;
  final double height;
  final String errorImg;
  final BoxFit fit;

  ///是否是圆图
  final bool isClipOval;

  LoadImage(
    this.imageUrl, {
    this.width,
    this.height,
    this.errorImg,
    this.fit,
    this.isClipOval = false,
  });

  @override
  Widget build(BuildContext context) {
    String _errorImg = errorImg ?? R.assetsImgCommonIconErrorImg;
    Widget child;

    if (imageUrl != null && imageUrl is Uint8List) {
      child = Image.memory(
        imageUrl,
        width: width,
        height: height,
        fit: fit,
      );
    } else if (Utils.strIsEmpty(imageUrl)) {
      child = Image.asset(
        _errorImg,
        width: width,
        height: height,
        fit: fit,
      );
    } else if (imageUrl.startsWith("http")) {
      child = CachedNetworkImage(
        imageUrl: imageUrl,
        width: width,
        height: height,
        fit: fit,
        placeholder: (context, url) => Container(
          width: width,
          height: height,
          child: SpinKitCircle(color: CommonColors.primary),
        ),
        errorWidget: (context, url, error) => Image.asset(
          _errorImg,
          width: width,
          height: height,
        ),
      );
    } else {
      child = Image.asset(
        imageUrl,
        width: width,
        height: height,
        fit: fit,
      );
    }

    return isClipOval ? ClipOval(child: child) : child;
  }
}
